import React from 'react';
import {Icon, Menu, Dropdown, Popover, Button, Spin, Modal} from 'antd';
import {WeaInput, WeaSelect, WeaLocaleProvider} from 'ecCom';
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
const getLabel = WeaLocaleProvider.getLabel;

const store = ['routing', 'weesoStore', 'weesoSeachSetStore']
@inject(...store)
@observer
export default class Weeso extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeoutMarker: undefined,
      topTabsWrapperWidth: 428
    };
    this.topTabsWrapper = React.createRef();
  }
  
  componentDidMount() {
  }
  
  componentDidUpdate(prevProps, prevState, prevContext) {
    const {weesoStore} = this.props;
    //tabs计算获得每个li的宽度
    let tabs = $('.weeso-tab-content li');
    //Object.keys(weesoStore.widthMap).length == 0  -- 保证只获取一次
    if (Object.keys(weesoStore.widthMap).length == 0 && tabs.length != 0) {
      tabs.map(item => {
        let itemWid = $('.weeso-tab-content li')[item].clientWidth
        weesoStore.widthMap[tabs[item].id] = itemWid
      })
      weesoStore.resortTopTaps();
    }
  
    //处理理由跳转之后，光标位置
    $('.input').focus();
    if(weesoStore.isRouting || weesoStore.isHotkeySearch){
      const inputNode = ReactDOM.findDOMNode(this.refs.inputNode);
      inputNode.setSelectionRange(weesoStore.selectionStart,weesoStore.selectionEnd)
      weesoStore.isRouting = false;
      weesoStore.isHotkeySearch = false;
    }
    this.setTopTabsWrapperWidth();
  }
  
  componentWillUnmount() {
    const { resortTopTaps } = this.props.weesoStore;
    resortTopTaps();
    window.clearTimeout(this.state.timeoutMarker);
  }
  
  setTopTabsWrapperWidth = () => {
    setTimeout(() => {
      if(this.topTabsWrapper && this.topTabsWrapper.current !== null && this.topTabsWrapper.current.offsetWidth) {
        let currentWidth = this.topTabsWrapper.current.offsetWidth+33;
        if(currentWidth > this.state.topTabsWrapperWidth) {
          this.setState({ topTabsWrapperWidth: currentWidth });
        }
      }
    }, 0);
  }

  render() {
    const { search } = this.props.routing.location;
    const {weesoStore, routing, weesoSeachSetStore} = this.props;
    let {defalutMoreKey, inputValue, hotkeys, iconClick, copiedcontentType1, copiedcontentType2, baseDadas} = weesoStore;
    let { search_type, page_descStr, setState } = this.props.weesoSeachSetStore;
    hotkeys = toJS(hotkeys);
    copiedcontentType1 = toJS(copiedcontentType1);
    copiedcontentType2 = toJS(copiedcontentType2);
    const placeHolder = weesoStore.defaultKey === 'CONTENT' ? getLabel(384222,'请输入搜索内容关键字') : getLabel(384223,'请输入搜索图片关键字');
    const hotkeysContent = (
      <ul className="input-hotkeys">
        { hotkeys && hotkeys.length != 0 && hotkeys.map((item, index) => {
          return <li
            className={index == weesoStore.myKey ? 'hotkeys-background' : 'hotkeys-hide-background'}
            ref="hotKey"
            key={index}
            onClick={() => {
              weesoStore.setState({inputValue: item});
              if(!weesoStore.isSearch && baseDadas.FLAG != -1){
                weesoStore.changeKey(weesoStore.defalutMoreKey, false);
                routing.push(`/main/esearch/result${search}`);
              }
              weesoStore.isShowSearchIcon = false;
              const { filterParams } = this.props.weesoSeachSetStore;
              let p = { page_search_json: JSON.stringify(filterParams())};
              weesoStore.preSearch(p);
            }}
          >{item}</li>
        })}
      </ul>
    )

    return (
      <div className="weeso-con">
        <div className="weeso-con-main">
          {this.props.hideTitle === "true" ?
            <div className='weeso-tab-hidetitle'>
              { page_descStr && page_descStr!== '' ? <div className="weeso-page_descStr">{ page_descStr }</div> : ''}
            </div>
            :
            search_type === 'ALL' ? <div className="weeso-tab " style={{ width: this.state.topTabsWrapperWidth }}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@t3jg5i`} className="weeso-tab-list" spinning={false}>
              <ul className="weeso-tab-content" ref={this.topTabsWrapper} >
                {copiedcontentType1 && copiedcontentType1.length != 0 && copiedcontentType1.map(item => {
                  return (
                    <li className={defalutMoreKey == item.key ? "weeso-tab-moredefault" : 'weeso-tab-defeault'}
                        id={item.key}
                        onClick={() => {
                          weesoStore.setState({
                            defalutMoreKey: item.key,
                            showToolPopover: false,
                            skipSearchParams: {
                              currentPage: 0,
                              lastRealNumber: 0,
                            },
                          });
                          weesoStore.commonInit();
                          weesoStore.changeKey(item.key);
                          weesoSeachSetStore.adSearchFormReset();
                          weesoSeachSetStore.getAdConditions();
                          weesoSeachSetStore.setState({ searchTagParams: {} }, () => {
                            const { filterParams } = this.props.weesoSeachSetStore;
                            let p = { page_search_json: JSON.stringify(filterParams())};
                            weesoStore.preSearch(p);
                          });
                        }}
                    >{item.name}</li>
                  )
                })}
              </ul>
              </Spin>
              {copiedcontentType2.length !== 0 &&
              <div className="tab-content-rest">
                <Dropdown ecId={`${this && this.props && this.props.ecId || ''}_Dropdown@5xakcl`}
                  trigger={['click']}
                  className="wea-weeso-dropdown"
                  overlay={
                    <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@depcxg`}>
                      {copiedcontentType2 && copiedcontentType2.length!==0 && copiedcontentType2.map((item, index) => {
                        return (
                          <li key={item.key}>
                            <span className={defalutMoreKey == item.key ? "weeso-tab-moredefault" : 'weeso-tab-defeault'}
                                  onClick={() => {
                                    weesoStore.setState({
                                      defalutMoreKey: item.key,
                                      showToolPopover: false,
                                      skipSearchParams: {
                                        currentPage: 0,
                                        lastRealNumber: 0,
                                      },
                                    });
                                    weesoStore.commonInit();
                                    weesoStore.changeKey(item.key);
                                    weesoStore.resortTopTaps();
                                    weesoSeachSetStore.adSearchFormReset();
                                    weesoSeachSetStore.setState({ searchTagParams: {} }, () => {
                                      const { filterParams } = this.props.weesoSeachSetStore;
                                      let p = { page_search_json: JSON.stringify(filterParams())};
                                      weesoStore.isSearch && weesoStore.preSearch(p);
                                    });
                                  }}
                            >{item.name}</span>
                          </li>
                        )
                      })}
                    </Menu>
                  }
                >
                  <a className="ant-dropdown-link" href="#">
                    <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@fa51z4`} type="down"/>
                  </a>
                </Dropdown>
              </div>}
            </div>
              : 
              ( page_descStr && page_descStr!== '' ? <div className="weeso-page_descStr">{ page_descStr }</div> : '')
          }
          <div className="weeeso-input">
            <div className="input-search">
             
              <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@9p980d`} visible={weesoStore.showHotKeys} placement="bottomLeft" content={hotkeysContent} trigger="click"
                       onVisibleChange={(v) => {
                         weesoStore.setState({showHotKeys: inputValue == '' ? false : v})
                       }}
                       style={{top: 84}}
                       overlayClassName="weeso-hotkeys-popover"
              >
                <input ref="inputNode"
                       placeholder={placeHolder}
                       className="input"
                       value={inputValue}
                       autoFocus="autoFocus"
                       onChange={e => {
                         this.inputChange(e.target.value);
                         weesoStore.setState({myKey: -1});
                         weesoSeachSetStore.setState({ searchTagParams: {} });
                        //  weesoSeachSetStore.adSearchFormReset();
                       }}
                       onKeyDown={(e) => {
                         this.myKeyDown(e);
                       }}
                />
              </Popover>
              {/* <span className="weeso-cursor input-text"
                    onClick={(e) => {
                      this.commonSearchFun(e);
                    }}
                    onMouseDown = {(e) => {
                      e.preventDefault(); //点击搜索，输入框不失去焦点
                    }}
              >{getLabel(197, "搜索")}</span> */}

              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t6djy1`} 
                type="primary"
                className="wesoo-search-btn"
                style={{borderRadius: 0,height: 36,width: 62,position: 'absolute'}}
                onClick={(e) => {
                  const { isSetServer, isSetServerMsg } = this.props.weesoStore;
                  if(isSetServer) {
                    this.commonSearchFun(e);
                  } else {
                    Modal.error({
                      title: getLabel(15172, "系统提示"),
                      content: <span className="content-img" dangerouslySetInnerHTML={{__html: isSetServerMsg}}/>,
                    });
                  }
                }}
                onMouseDown = {(e) => {
                  e.preventDefault(); //点击搜索，输入框不失去焦点
                }}
              >{getLabel(197, "搜索")}</Button>
              
            </div>
            
            <div className="input-left">
              <div className="flip-container" onClick={this.onClick}>
                <div className={iconClick ? "click" : "flipper"}>
                  <div className={iconClick ? 'back weeso-cursor' : 'front weeso-cursor'}>
                    <em title={getLabel(127014, "搜索内容")} className="icon-coms-Journal"></em>
                  </div>
                  <div className={iconClick ? 'front weeso-cursor' : 'back weeso-cursor'}>
                    <em title={getLabel(384225, "搜索图片")} className="icon-coms-chart"></em>
                  </div>
                </div>
              </div>
              <span className="input-line"></span>
            </div>
          </div>
        </div>
      </div>
    )
  }
  
  //input框改变回调
  inputChange = (value) => {
    const {weesoStore} = this.props;
    weesoStore.setState({
      previousInputValue: weesoStore.inputValue,
      inputValue: value,
      currentInputValue: value,
      isSearchSucess: false
    });
    this.searchDelay();
  }
  
  //图片翻转效果
  onClick = (e) => {
    const {weesoStore} = this.props;
    const { filterParams } = this.props.weesoSeachSetStore;
    weesoStore.setState({
      iconClick: !weesoStore.iconClick,
      defaultKey: weesoStore.iconClick ? 'CONTENT' : 'PICTURE',
      skipSearchParams: {
        currentPage: 0,
        lastRealNumber: 0,
      },
    })
    weesoStore.commonInit();
    weesoStore.preSearch({ page_search_json: JSON.stringify(filterParams()) });
    // !weesoStore.isLocked && weesoStore.preSearch();
  }
  
  //延时搜索
  searchDelay = (value) => {
    const {weesoStore} = this.props;
    if (this.state.timeoutMarker) {
      window.clearTimeout(this.state.timeoutMarker)
    }
    this.setState({
      timeoutMarker: setTimeout(() => {
        let previousValue = weesoStore.previousInputValue;
        if (weesoStore.inputValue && previousValue != weesoStore.inputValue) {
          !weesoStore.isSearchSucess && weesoStore.setState({showHotKeys: true})
          weesoStore.getAssociate({key: weesoStore.inputValue});
        }
        if (!weesoStore.inputValue) {
          weesoStore.setState({showHotKeys: false})
          window.clearTimeout(this.state.timeoutMarker);
        }
      }, 300)
    });
  }
  
  //键盘事件
  myKeyDown = (e) => {
    const {weesoStore, routing} = this.props;
    let {myKey, hotkeys, showHotKeys, currentInputValue} = weesoStore;
    hotkeys = toJS(hotkeys);
    
    if (e.keyCode == 13) {
      this.commonSearchFun(e);
    } else if (e.keyCode == 40) {
      if (showHotKeys && hotkeys.length != 0) {
        if (myKey < hotkeys.length - 1 && myKey >= -1) {
          weesoStore.setState({myKey: myKey + 1, inputValue: hotkeys[myKey + 1]})
        } else {
          weesoStore.setState({myKey: -1, inputValue: currentInputValue})
        }
      }
    } else if (e.keyCode == 38) {
      e.preventDefault();//阻止光标的默认事件
      if (showHotKeys && hotkeys.length != 0) {
        if (myKey > 0) {
          weesoStore.setState({myKey: myKey - 1, inputValue: hotkeys[myKey - 1]})
        } else if (myKey == 0) {
          weesoStore.setState({myKey: -1, inputValue: currentInputValue})
        } else {
          weesoStore.setState({myKey: hotkeys.length - 1, inputValue: hotkeys[hotkeys.length - 1]})
        }
      }
    }
  }
  
  //点击按钮搜索和enter搜索共同方法
  commonSearchFun = (e) => {
    const {weesoStore, routing} = this.props;
    e.preventDefault();//阻止光标的默认事件
    //获得光标位置
    const inputNode = ReactDOM.findDOMNode(this.refs.inputNode);
    weesoStore.setState({
      inputNode: ReactDOM.findDOMNode(this.refs.inputNode),
      selectionStart: inputNode.selectionStart,
      selectionEnd: inputNode.selectionEnd,
      skipSearchParams: {
        currentPage: 0,
        lastRealNumber: 0,
      },
    })
    
    if(!weesoStore.isSearch && weesoStore.inputValue !== ''){
      weesoStore.isRouting = true;
      weesoStore.changeKey(weesoStore.defalutMoreKey, false);
      // weesoStore.baseDadas.FLAG != -1 && routing.push('/main/esearch/result');
      weesoStore.baseDadas.FLAG != -1 && this.pushRouter();
    }
    weesoStore.commonInit();
    const { search } = this.props.routing.location;
    if(search.indexOf('type=') < 0 && (weesoStore.inputValue === undefined || weesoStore.inputValue === '')) {
      routing.push(`/main/esearch/weeso${search}`);
    } else {
      const { filterParams } = this.props.weesoSeachSetStore;
      weesoStore.preSearch({ page_search_json: JSON.stringify(filterParams()) });
    }
  }

  pushRouter = () => {
    const { search } = this.props.routing.location;
    let page_uuid = this.props.routing.location && this.props.routing.location.query &&  this.props.routing.location.query.page_uuid;
    // if(page_uuid) {
    //   this.props.routing.push(`/main/esearch/result?page_uuid=${page_uuid}`);
    // } else {
    // }
    this.props.routing.push(`/main/esearch/result${search}`);
  }


}